using Microsoft.EntityFrameworkCore;
using Universal.Application.Common;
using Universal.Application.Contracts.Common;
using Universal.Application.Contracts.Dto.User;
using Universal.Application.Repositories;
using Universal.Domain.Entities.App;
using Universal.Domain.Repositories;

namespace Universal.Application.Services;

public class UserService : IUserService
{
    private readonly IRepository<AppUser> _userRepository;
    private readonly IRepository<AppRole> _roleRepository;
    private readonly ILogService _logService;
    public UserService(IRepository<AppUser> userRepository, IRepository<AppRole> roleRepository, ILogService logService)
    {
        _userRepository = userRepository;
        _roleRepository = roleRepository;
        _logService = logService;
    }

    /// <summary>
    /// 新增用户
    /// </summary>
    /// <param name="addUserDto">新增用户信息</param>
    public async Task<dynamic> AddUserAsync(AddEditUserDto addUserDto)
    {
        var users = await _userRepository.GetAllAsync();
        if (users.Any(u => u.Username == addUserDto.Username || u.Email == addUserDto.Email || u.Phone == addUserDto.Phone))
        {
            return ApiResponse<string>.Failure(5001, "用户已存在，请确认后重试!!");
        }

        // 设置默认密码
        var defaultPassword = "abc123456";
        var hashedPassword = PasswordHasher.HashPassword(defaultPassword);

        // 设置默认头像
        var defaultAvatar = "https://ts1.tc.mm.bing.net/th/id/OIP-C.UyaBji0AU_6M3VDA2F1RvgAAAA?rs=1&pid=ImgDetMain&o=7&rm=3";

        var user = new AppUser
        {
            Username = addUserDto.Username,
            Nickname = addUserDto.Nickname,
            Email = addUserDto.Email,
            Phone = addUserDto.Phone,
            IsActive = addUserDto.IsActive,
            CreatedAt = DateTime.UtcNow,
            UpdatedAt = DateTime.UtcNow,
            Password = hashedPassword,
            Avatar = defaultAvatar,
        };
        await _userRepository.AddAsync(user);
        if (addUserDto.RoleIds != null)
        {
            foreach (var roleId in addUserDto.RoleIds)
            {
                var role = await _roleRepository.GetByIdAsync(roleId);
                if (role != null)
                {
                    user.Roles.Add(role);
                }
            }
        }

        await _logService.WriteLogAsync($"新增用户{addUserDto.Username}成功");

        await _userRepository.UpdateAsync(user);
        return ApiResponse<string>.Success("新增用户成功", "新增成功，默认密码：abc123456");
    }

    /// <summary>
    /// 删除用户
    /// </summary>
    /// <param name="userId">用户ID</param>
    /// <returns>返回结果</returns>
    public async Task<dynamic> DeleteUserAsync(Guid userId)
    {
        var user = await _userRepository.GetByIdWithIncludesAsync(userId, u => u.Roles);
        if (user == null)
        {
            return ApiResponse<string>.Failure(5001, "用户不存在");
        }

        // 检查用户是否拥有超级管理员角色
        if (user.Roles.Any(role => role.Rolename == "超级管理员"))
        {
            return ApiResponse<string>.Failure(5002, "超级管理员用户无法删除！！");
        }

        await _userRepository.DeleteAsync(user);
        return ApiResponse<string>.Success("删除成功");
    }

    // 禁用用户
    public async Task<dynamic> DisableUserAsync(Guid userId)
    {
        var user = await _userRepository.GetByIdAsync(userId);
        if (user == null)
        {
            return ApiResponse<string>.Failure(5001, "用户不存在");
        }
        if (user.IsActive == false)
        {
            return ApiResponse<string>.Failure(5002, "用户已禁用,无需重复禁用");
        }
        user.IsActive = false;
        await _userRepository.UpdateAsync(user);
        return ApiResponse<string>.Success("禁用成功");
    }

    /// <summary>
    /// 编辑用户
    /// </summary>
    /// <param name="editUserDto">编辑用户信息</param>
    /// <returns>返回结果</returns>
    public async Task<dynamic> EditUserAsync(Guid id, AddEditUserDto editUserDto)
    {
        var user = await _userRepository.GetByIdWithIncludesAsync(id, u => u.Roles);
        if (user == null)
        {
            return ApiResponse<string>.Failure(5003, "用户不存在");
        }

        user.Nickname = editUserDto.Nickname;
        user.Email = editUserDto.Email;
        user.Phone = editUserDto.Phone;
        user.IsActive = editUserDto.IsActive;
        // user.Description = editUserDto.Description;
        user.UpdatedAt = DateTime.UtcNow;

        user.Roles.Clear();

        if (editUserDto.RoleIds != null)
        {
            foreach (var roleId in editUserDto.RoleIds)
            {
                var role = await _roleRepository.GetByIdAsync(roleId);
                if (role != null)
                {
                    user.Roles.Add(role);
                }
            }
        }

        await _userRepository.UpdateAsync(user);
        return ApiResponse<string>.Success("修改成功");
    }

    public async Task<dynamic> EnableUserAsync(Guid userId)
    {
        var user = await _userRepository.GetByIdAsync(userId);
        if (user == null)
        {
            return ApiResponse<string>.Failure(5001, "用户不存在");
        }
        if (user.IsActive == true)
        {
            return ApiResponse<string>.Failure(5002, "用户已启用,无需重复启用");
        }
        user.IsActive = true;
        await _userRepository.UpdateAsync(user);
        return ApiResponse<string>.Success("启用成功");
    }

    /// <summary>
    /// 获取当前用户个人信息
    /// </summary>
    /// <param name="userId"></param>
    /// <returns></returns>
    public async Task<dynamic> GetCurrentUserProfileAsync(Guid userId)
    {
        var user = await _userRepository.GetByIdAsync(userId);
        if (user == null)
        {
            return ApiResponse<string>.Failure(5001, "用户不存在");
        }
        var userProfile = new UserProfileDto
        {
            Nickname = user.Nickname,
            Email = user.Email,
            Phone = user.Phone,
            Description = user.Description,
            Avatar = user.Avatar,
        };

        return ApiResponse<UserProfileDto>.Success(userProfile);
    }

    public async Task<ApiResponse<PagedResult<UsersViewDto>>> GetUsersPagedAsync(int pageIndex, int pageSize)
    {
        // 获取分页数据，包含导航属性Roles
        var (users, totalCount) = await _userRepository.GetPagedAsync(pageIndex, pageSize, u => u.Roles);

        // 转换为DTO，包含完整的角色信息
        var userDtos = users.Select(user => new UsersViewDto(
            user.Id,
            user.Username,
            user.Nickname ?? string.Empty,
            user.Email,
            user.Phone,
            user.Avatar,
            user.IsActive,
            user.CreatedAt,
            user.Roles.Select(r => new UserViewRoleDto(r.Id, r.Rolename, r.IsActive))
        ));

        var pagedResult = new PagedResult<UsersViewDto>
        {
            TotalCount = totalCount,
            TotalPages = (int)Math.Ceiling(totalCount / (double)pageSize),
            PageIndex = pageIndex,
            PageSize = pageSize,
            Items = userDtos.ToList()
        };

        return ApiResponse<PagedResult<UsersViewDto>>.Success(pagedResult);
    }

    /// <summary>
    /// 模糊查询用户 - 支持多字段and条件查询（简化版本）
    /// </summary>
    /// <param name="query">查询参数</param>
    /// <returns>分页用户数据</returns>
    public async Task<ApiResponse<PagedResult<UsersViewDto>>> QueryUsersAsync(UserQueryDto query)
    {
        if (query == null)
        {
            return ApiResponse<PagedResult<UsersViewDto>>.Failure(4001, "查询参数不能为空");
        }

        var baseQuery = _userRepository.Query();

        // 检查是否有任何查询条件
        var hasUsername = !string.IsNullOrWhiteSpace(query.Username);
        var hasNickname = !string.IsNullOrWhiteSpace(query.Nickname);
        var hasPhone = !string.IsNullOrWhiteSpace(query.Phone);
        var hasEmail = !string.IsNullOrWhiteSpace(query.Email);
        var hasRoleIds = query.RoleIds != null && query.RoleIds.Any();
        var hasIsActive = query.IsActive;

        // 应用 AND 逻辑：所有条件都必须满足
        if (hasUsername)
        {
            baseQuery = baseQuery.Where(u => u.Username.Contains(query.Username!));
        }

        if (hasNickname)
        {
            baseQuery = baseQuery.Where(u => u.Nickname != null && u.Nickname.Contains(query.Nickname!));
        }

        if (hasPhone)
        {
            baseQuery = baseQuery.Where(u => u.Phone.Contains(query.Phone!));
        }

        if (hasEmail)
        {
            baseQuery = baseQuery.Where(u => u.Email.Contains(query.Email!));
        }

        if (hasRoleIds)
        {
            baseQuery = baseQuery.Where(u => u.Roles.Any(r => query.RoleIds!.Contains(r.Id)));
        }

        if (hasIsActive.HasValue)
        {
            baseQuery = baseQuery.Where(u => u.IsActive == query.IsActive!.Value);
        }

        // 包含角色导航属性
        var queryable = baseQuery.Include(u => u.Roles);

        var totalCount = await queryable.CountAsync();

        var users = await queryable
            .OrderByDescending(u => u.CreatedAt)
            .Skip((query.PageIndex - 1) * query.PageSize)
            .Take(query.PageSize)
            .ToListAsync();

        // 转换为DTO
        var userDtos = users.Select(user => new UsersViewDto(
            user.Id,
            user.Username,
            user.Nickname ?? string.Empty,
            user.Email,
            user.Phone,
            user.Avatar,
            user.IsActive,
            user.CreatedAt,
            user.Roles.Select(r => new UserViewRoleDto(r.Id, r.Rolename, r.IsActive))
        ));

        var pagedResult = new PagedResult<UsersViewDto>
        {
            Items = userDtos,
            TotalCount = totalCount,
            TotalPages = (int)Math.Ceiling(totalCount / (double)query.PageSize),
            PageIndex = query.PageIndex,
            PageSize = query.PageSize
        };

        return ApiResponse<PagedResult<UsersViewDto>>.Success(pagedResult);
    }

    /// <summary>
    /// 分配角色
    /// </summary>
    public async Task<dynamic> AssignRolesAsync(AssignRolesDto assignRolesDto)
    {
        var user = await _userRepository.GetByIdAsync(assignRolesDto.UserId);

        if (user == null)
        {
            return ApiResponse<string>.Failure(5001, "用户不存在");
        }
        var roleIds = assignRolesDto.RoleIds;
        if (roleIds == null)
        {
            return ApiResponse<string>.Failure(5002, "角色ID不能为空");
        }
        // 检查角色是否存在
        foreach (var roleId in roleIds)
        {
            var role = await _roleRepository.GetByIdAsync(roleId);
            if (role == null)
            {
                return ApiResponse<string>.Failure(5003, "角色不存在");
            }
            user.Roles.Add(role);
        }

        await _userRepository.UpdateAsync(user);
        return ApiResponse<string>.Success("分配角色成功");
    }

    public async Task<dynamic> RemoveRolesAsync(AssignRolesDto assignRolesDto)
    {
        var user = await _userRepository.GetByIdAsync(assignRolesDto.UserId);

        if (user == null)
        {
            return ApiResponse<string>.Failure(5001, "用户不存在");
        }
        var roleIds = assignRolesDto.RoleIds;
        if (roleIds == null)
        {
            return ApiResponse<string>.Failure(5002, "角色ID不能为空");
        }
        // 检查角色是否存在
        foreach (var roleId in roleIds)
        {
            var role = await _roleRepository.GetByIdAsync(roleId);
            if (role == null)
            {
                return ApiResponse<string>.Failure(5003, "角色不存在");
            }
            user.Roles.Remove(role);
        }

        await _userRepository.UpdateAsync(user);
        return ApiResponse<string>.Success("移除角色成功");
    }

    /// <summary>
    /// 更新头像
    /// </summary>
    /// <param name="userId"></param>
    /// <param name="avatarUrl"></param>
    /// <returns></returns>
    public async Task<dynamic> UpdateAvatarAsync(Guid userId, string avatarUrl)
    {
        var user = await _userRepository.GetByIdAsync(userId);
        if (user == null)
        {
            return ApiResponse<string>.Failure(5001, "用户不存在");
        }

        user.Avatar = avatarUrl;
        await _userRepository.UpdateAsync(user);
        return ApiResponse<string>.Success("头像更新成功");
    }


    /// <summary>
    /// 修改个人中心
    /// </summary>
    /// <param name="userId">用户ID</param>
    /// <param name="userProfileDto">用户信息</param>
    /// <returns>返回结果</returns>
    public async Task<dynamic> UpdateUserProfileAsync(Guid userId, UpdateUserProfileDto updateUserProfileDto)
    {
        var user = await _userRepository.GetByIdAsync(userId);
        if (user == null)
        {
            return ApiResponse<string>.Failure(5001, "用户不存在");
        }

        user.Nickname = updateUserProfileDto.Nickname;
        user.Email = updateUserProfileDto.Email;
        user.Phone = updateUserProfileDto.Phone;
        user.Description = updateUserProfileDto.Description;

        await _userRepository.UpdateAsync(user);

        return ApiResponse<string>.Success("修改成功");
    }

    public async Task<dynamic> QueryRoleView()
    {
        var roles = await _roleRepository.GetAllAsync();
        var rolesDto = roles.Select(role => new QueryRoleDto
        (
            role.Id,
            role.Rolename
        )).ToList();

        return ApiResponse<List<QueryRoleDto>>.Success(rolesDto);
    }


}